<template>
  <view class="login-container">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">温室自动卷帘助手</text>
      <text class="subtitle">走进智慧农业，创建幸福生活</text>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <view class="form-tabs">
        <view
          class="tab"
          :class="{ active: choose_login_way }"
          @click="choose_login_way = true"
        >账号密码登录</view>
        <view
          class="tab"
          :class="{ active:!choose_login_way }"
          @click="choose_login_way = false"
        >邮箱验证登录</view>
        <view
          class="tab-line"
          :style="{
            width: choose_login_way? '300rpx' : '300rpx',
            transform: `translateX(${choose_login_way? 0 : '125%'})`
          }"
        ></view>
      </view>

      <!-- 账号登录 -->
      <view v-if="choose_login_way">
        <view class="form-item">
          <uni-icons type="phone" size="30"></uni-icons>
          <span style="margin-right: 10px;"></span>
          <input type="text" placeholder="请输入手机号" v-model="formData.phone" @input="validateForm()"/>
		  <text v-if="errors.phone" class="error-tip">请输入有效的11位手机号</text>
        </view>
        <view class="form-item">
          <uni-icons type="locked" size="30"></uni-icons>
          <span style="margin-right: 10px;"></span>
          <input type="password" placeholder="请输入密码" v-model="formData.password" @input="validateForm()"/>
		  <text v-if="errors.password" class="error-tip">密码需6-20位，包含字母和数字</text>
        </view>
        <button class="login-btn" @click="handleLogin">登 录</button>		
      </view>
      <!-- 账号登录 -->
      <!-- 手机号验证登录 -->
      <view v-if="!choose_login_way">
        <!-- <view class="form-item">
          <uni-icons type="phone" size="30"></uni-icons>
          <span style="margin-right: 10px;"></span>
          <input type="text" placeholder="请输入手机号" v-model="formData.phone"/>
        </view> -->
		<view class="form-item">
		  <uni-icons type="mail-open" size="30"></uni-icons>
		  <span style="margin-right: 10px;"></span>
		  <input type="text" placeholder="请输入邮箱" v-model="formData.usermail" @input="validateForm()"/>
		  <text v-if="errors.email" class="error-tip">请输入有效的邮箱地址</text>
		  <button class="getAccesscode"  @click="handleGetSms" :disabled="isCounting"  >{{countDownText}}</button>
		</view>
        <view class="form-item">
          <uni-icons type="locked" size="30"></uni-icons>
          <span style="margin-right: 10px;"></span>
          <input type="password" placeholder="请输入验证码" v-model="formData.smsCode" @input="validateForm()"/>
		  <text v-if="errors.code" class="error-tip">请输入6位验证码</text>
        </view>
        <button class="login-btn" @click="VerifyLogin">登 录</button>
      </view>
      <!-- 手机号验证登录 -->
    </view>

    <!-- 第三方登录 -->
    <view class="third-party">
      <view class="phone-login">
        <text>没有账号？</text>
        <text class="highlight" @click="handleRegister">点击注册</text>
      </view>
    </view>
    <!-- 第三方登录-->
</view>
</template>

<script setup>
// Vue 3 Composition API
import { reactive, ref ,computed, onUnmounted} from 'vue';

// 正则表达式
const phoneReg = /^1[3-9]\d{9}$/; // 手机号正则
const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; // 邮箱正则
const passwordReg = /^(?=.*\d)(?=.*[a-zA-Z])[0-9a-zA-Z]{6,20}$/; // 密码正则（至少6位，包含字母和数字）
const nicknameReg = /^[\u4e00-\u9fa5a-zA-Z0-9_]{2,10}$/; // 昵称正则（2-10位，支持中文、字母、数字、下划线）

// 错误提示状态
const errors = reactive({
  phone: false,
  email: false,
  password: false,
  nickname: false,
  code: false
});

const validateForm = () => {
  // 使用空字符串默认值避免 undefined
  const phone = formData.phone || '';
  const email = formData.usermail || '';
  const password = formData.password || '';
  const nickname = formData.name || '';
  const code = formData.smscode || '';

  errors.phone = !phoneReg.test(phone);
  errors.email = !emailReg.test(email);
  errors.password = !passwordReg.test(password);
  errors.nickname = !nicknameReg.test(nickname);
  errors.code = code.length !== 6; // 安全访问 length

  return !Object.values(errors).some(error => error);
};

// 倒计时状态管理
const countdown = ref(30);
const isCounting = ref(false);
let timer = null;

// 计算按钮显示文本
const countDownText = computed(() => {
  return isCounting.value 
    ? `剩余 ${countdown.value} 秒` 
    : "获取验证码";
});



// 登录方式状态
const choose_login_way = ref(true);

let formData = reactive({
  phone: '',
  password: '',
  smsCode: '',
  usermail: '',
})


// 获取验证码逻辑
const handleGetSms = async () => {
  // 防止重复点击
  if (isCounting.value) return;

  try {
    
	const response = await uni.request({
		url: 'http://192.168.43.1:8080/loginBymailGetcode',
		method: 'POST',
		header: {
		  'Content-Type': 'application/json'
		},
		data: {usermail : formData.usermail},
		timeout: 5000 // 增加5秒超时设置
	});
    if(response.data.code === 2003){
    	uni.showToast({
    		title: '验证码已发送',
			icon: 'none'
    	});
    }
    else{
    	uni.showToast({
    		title:  response.data.msg || '发送验证码失败',
			icon: 'none'
    	});
    }
    
    // 启动倒计时
    isCounting.value = true;
    countdown.value = 30;
    
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
        isCounting.value = false;
      }
    }, 1000);
    
  } catch (error) {
    console.error('获取验证码失败:', error.message);
    // 失败时重置倒计时状态
    isCounting.value = false;
  }
};


//验证码登录
const VerifyLogin = async () => {
  try {
	const response = await uni.request({
		url: 'http://192.168.43.1:8080/verifyCode',
		method: 'POST',
		header: {
		  'Content-Type': 'application/json'
		},
		data: {
				usermail : formData.usermail,
				smscode : formData.smsCode
			},
		timeout: 5000 // 增加5秒超时设置
	});
	console.log(response.data.code);
    if(response.data.code === 2001){
    	uni.showToast({
    		title: '登录成功',
			icon: 'none'
    	});
		uni.navigateTo({
			url:'/pages/index/Index'
		})
    }
    else{
    	uni.showToast({
    		title: '登录失败',
			icon: 'none'
    	});
    }
    
  } catch (error) {
    console.error('登录失败:', error.message);
  }
};

//处理注册
const handleRegister = ()=>{
	uni.navigateTo({
		url:'/pages/register/Register'
	})
}


// 登录处理函数
const handleLogin = async () => {
  try {
    if (formData.phone.length !== 11) {
      uni.showToast({ title: '手机号必须为11位', icon: 'none' });
      return;
    }

    uni.showLoading({ title: '请稍后...', mask: true });
    
    const requestData = {
      phone: formData.phone,
      password: formData.password
    } ;

    const res = await uni.request({
      url: 'http://192.168.43.1:8080/login',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: requestData,
      timeout: 5000 // 增加5秒超时设置
    });

    uni.hideLoading();
    if (res.data.code === 1001) {
	// 存储用户信息到本地
	  uni.setStorageSync('userInfo', {
		phone: res.data.data.userphonenumber,
		nickname: res.data.data.username ,
		password: res.data.data.userpassword
	  });
      uni.showToast({ title: '登录成功', icon: 'success' });
      uni.navigateTo({ url: '/pages/index/Index' });
    } else {
      uni.showToast({ title: res.data.msg || '登录失败', icon: 'none' });
    }
  } catch (error) {
    uni.hideLoading();
    // 新增网络错误判断
    if (error.errMsg.includes('request:fail') || error.statusCode === 0) {
      uni.showToast({ title: '网络连接失败，请检查网络设置', icon: 'none' });
    } else {
      uni.showToast({ title: '请求异常，请稍后重试', icon: 'none' });
    }
    console.error('登录错误:', error);
  }
};


// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) clearInterval(timer);
});

</script>

<style>
/* 全局样式 */
page {
	background: linear-gradient(180deg, #a8e6e6 0%, #e8f4f8 100%);
	min-height: 100%;
	/* 背景图片设置 */
    background-image: url('/static/images/loginpagebackground.jpg');
    background-size: cover; /* 覆盖整个容器 */
    background-position: center; /* 居中显示 */
    background-repeat: no-repeat; /* 禁止重复 */
}

.error-tip {
  font-size: 24rpx;
  color: #55aaff;
  margin-left: 60rpx;
  height: 30rpx;
  line-height: 30rpx;
}

/* 容器样式 */
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
  min-height: 100hv;
}

/* 头部标题样式 */
.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 180rpx;
  margin-bottom: 100rpx;
}

.title {
  font-size: 80rpx;
  font-weight: bold;
  color: #2aaa9b;
  margin-bottom: 20rpx;
}

.subtitle {
  font-size: 28rpx;
  color: #000000;
}

/* 登录表单 */
.login-form {
  width: 100%;
  height: auto;
  /* background-color: #fff; */
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 60rpx;
  
	background-color: rgba(255, 255, 255, 0.5); /* 白色半透明（最后一位为透明度，0-1） */
	/* 新增样式 */
	border-radius: 20rpx; /* 更大圆角，更柔和 */
	box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05); /* 增强立体感 */
	backdrop-filter: blur(15rpx); /* 毛玻璃效果，需配合定位 */
	position: relative; /* 毛玻璃效果需要 */
}

.form-tabs {
  display: flex;
  position: relative;
  border-bottom: 2rpx solid #eee;
  margin-bottom: 30rpx;
}

.getAccesscode {
	background-color: #2aaa9b;
	color: white;
    height: 50rpx;
    line-height: 50rpx;
    border-radius: 10rpx;
    font-size: 24rpx;
    margin-left: 10px;
    border: none;
    cursor: pointer;
}



.getAccesscode:disabled {
  background-color: #79aaa4;
  cursor: not-allowed;
}


.tab {
  font-size: 28rpx;
  color: #666;
  padding-bottom: 15rpx;
  margin-right: 0;
  margin-left: 0;
  flex: 1;
  text-align: center;
  cursor: pointer;
  transition: color 0.8s;
}

.tab.active {
  color: #2aaa9b;
  font-weight: bold;
}

.tab-line {
  position: absolute;
  bottom: 0;
  height: 4rpx;
  background-color: #2aaa9b;
  transition: transform 0.5s ease;
  transform-origin: left center;
}

.form-item {
  display: flex;
  align-items: center;
  border-bottom: 2rpx solid #eee;
  padding: 25rpx 0;
  margin-bottom: 20rpx;
}

.icon-user,
.icon-lock {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
  color: #999;
}

input {
  flex: 1;
  font-size: 28rpx;
}

.login-btn {
  background-color: #4cbfba;
  color: white;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 25rpx;
  font-size: 32rpx;
  margin-top: 50rpx;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #3aa39f;
}

/* 第三方登录 */
.third-party {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 60rpx;
}

.phone-login {
  font-size: 28rpx;
  background-color: rgba(255, 255, 255, 0.5); /* 设置背景为半透明白色 */
  backdrop-filter: blur(10px); /* 添加毛玻璃效果 */
  border: 1rpx solid #ffffff; /* 添加边框（可选，原代码缺少边框宽度和样式） */
  border-radius: 16rpx; /* 添加圆角 */
  height: 40rpx;
  width: auto;
  padding-left: 18rpx;
  padding-right: 18rpx;
  display: flex;
}

.highlight {
  color: #2aaa9b;
  margin-left: 10rpx;
  cursor: pointer;
}
</style>